"""
进程监控页面
表格显示进程信息，支持搜索过滤和结束进程操作
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, 
                             QTableWidgetItem, QLineEdit, QPushButton, QLabel,
                             QMessageBox, QHeaderView, QAbstractItemView)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont


class ProcessTab(QWidget):
    """进程监控页面"""
    
    # 定义信号
    kill_process_signal = pyqtSignal(int)  # 结束进程信号
    
    def __init__(self):
        super().__init__()
        self.processes_data = []  # 存储进程数据
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout()
        layout.setSpacing(10)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 创建搜索栏
        search_layout = self.create_search_bar()
        layout.addLayout(search_layout)
        
        # 创建进程表格
        self.create_process_table()
        layout.addWidget(self.process_table)
        
        # 创建操作按钮栏
        button_layout = self.create_button_bar()
        layout.addLayout(button_layout)
        
        # 创建状态栏
        status_layout = self.create_status_bar()
        layout.addLayout(status_layout)
        
        self.setLayout(layout)
    
    def create_search_bar(self) -> QHBoxLayout:
        """创建搜索栏"""
        layout = QHBoxLayout()
        
        # 搜索标签
        search_label = QLabel("搜索进程:")
        search_label.setFont(QFont("Microsoft YaHei", 10))
        layout.addWidget(search_label)
        
        # 搜索输入框
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入进程名称或PID进行搜索...")
        self.search_input.setFont(QFont("Microsoft YaHei", 10))
        self.search_input.textChanged.connect(self.filter_processes)
        layout.addWidget(self.search_input)
        
        # 清空搜索按钮
        clear_button = QPushButton("清空")
        clear_button.setFont(QFont("Microsoft YaHei", 9))
        clear_button.clicked.connect(self.clear_search)
        layout.addWidget(clear_button)
        
        return layout
    
    def create_process_table(self):
        """创建进程表格"""
        self.process_table = QTableWidget()
        
        # 设置表格列
        columns = ["PID", "进程名称", "CPU使用率(%)", "内存使用率(%)", "内存(MB)", "状态"]
        self.process_table.setColumnCount(len(columns))
        self.process_table.setHorizontalHeaderLabels(columns)
        
        # 设置表格属性
        self.process_table.setAlternatingRowColors(True)
        self.process_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.process_table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.process_table.setSortingEnabled(True)
        
        # 设置表格样式
        self.process_table.setStyleSheet("""
            QTableWidget {
                gridline-color: #d0d0d0;
                background-color: white;
                alternate-background-color: #f5f5f5;
            }
            QTableWidget::item {
                padding: 5px;
            }
            QTableWidget::item:selected {
                background-color: #3daee9;
                color: white;
            }
            QHeaderView::section {
                background-color: #e0e0e0;
                padding: 8px;
                border: 1px solid #d0d0d0;
                font-weight: bold;
            }
        """)
        
        # 设置列宽
        header = self.process_table.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.Fixed)  # PID
        header.setSectionResizeMode(1, QHeaderView.Stretch)  # 进程名称
        header.setSectionResizeMode(2, QHeaderView.Fixed)  # CPU使用率
        header.setSectionResizeMode(3, QHeaderView.Fixed)  # 内存使用率
        header.setSectionResizeMode(4, QHeaderView.Fixed)  # 内存MB
        header.setSectionResizeMode(5, QHeaderView.Fixed)  # 状态
        
        self.process_table.setColumnWidth(0, 80)   # PID
        self.process_table.setColumnWidth(2, 100)  # CPU使用率
        self.process_table.setColumnWidth(3, 100)  # 内存使用率
        self.process_table.setColumnWidth(4, 100)  # 内存MB
        self.process_table.setColumnWidth(5, 80)   # 状态
        
        # 设置字体
        self.process_table.setFont(QFont("Microsoft YaHei", 9))
    
    def create_button_bar(self) -> QHBoxLayout:
        """创建操作按钮栏"""
        layout = QHBoxLayout()
        
        # 刷新按钮
        refresh_button = QPushButton("刷新进程列表")
        refresh_button.setFont(QFont("Microsoft YaHei", 10))
        refresh_button.clicked.connect(self.refresh_processes)
        layout.addWidget(refresh_button)
        
        layout.addStretch()
        
        # 结束进程按钮
        self.kill_button = QPushButton("结束选中进程")
        self.kill_button.setFont(QFont("Microsoft YaHei", 10))
        self.kill_button.setStyleSheet("""
            QPushButton {
                background-color: #f44336;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
            }
            QPushButton:hover {
                background-color: #d32f2f;
            }
            QPushButton:pressed {
                background-color: #b71c1c;
            }
            QPushButton:disabled {
                background-color: #cccccc;
                color: #666666;
            }
        """)
        self.kill_button.clicked.connect(self.kill_selected_process)
        self.kill_button.setEnabled(False)
        layout.addWidget(self.kill_button)
        
        # 连接选择变化信号
        self.process_table.itemSelectionChanged.connect(self.on_selection_changed)
        
        return layout
    
    def create_status_bar(self) -> QHBoxLayout:
        """创建状态栏"""
        layout = QHBoxLayout()
        
        self.status_label = QLabel("进程数量: 0")
        self.status_label.setFont(QFont("Microsoft YaHei", 9))
        layout.addWidget(self.status_label)
        
        layout.addStretch()
        
        self.update_time_label = QLabel("最后更新: --")
        self.update_time_label.setFont(QFont("Microsoft YaHei", 9))
        layout.addWidget(self.update_time_label)
        
        return layout
    
    def update_data(self, system_info: dict):
        """更新进程数据"""
        try:
            import time
            
            # 获取进程列表
            processes = system_info.get('processes', [])
            self.processes_data = processes
            
            # 更新表格
            self.populate_table(processes)
            
            # 更新状态栏
            self.status_label.setText(f"进程数量: {len(processes)}")
            current_time = time.strftime("%H:%M:%S")
            self.update_time_label.setText(f"最后更新: {current_time}")
            
        except Exception as e:
            print(f"更新进程数据失败: {e}")
    
    def populate_table(self, processes: list):
        """填充表格数据"""
        try:
            # 获取当前搜索文本
            search_text = self.search_input.text().lower()
            
            # 过滤进程
            if search_text:
                filtered_processes = []
                for proc in processes:
                    if (search_text in proc['name'].lower() or 
                        search_text in str(proc['pid'])):
                        filtered_processes.append(proc)
                processes = filtered_processes
            
            # 设置表格行数
            self.process_table.setRowCount(len(processes))
            
            # 填充数据
            for row, proc in enumerate(processes):
                # PID
                pid_item = QTableWidgetItem(str(proc['pid']))
                pid_item.setTextAlignment(Qt.AlignCenter)
                self.process_table.setItem(row, 0, pid_item)
                
                # 进程名称
                name_item = QTableWidgetItem(proc['name'])
                self.process_table.setItem(row, 1, name_item)
                
                # CPU使用率
                cpu_item = QTableWidgetItem(f"{proc['cpu_percent']:.1f}")
                cpu_item.setTextAlignment(Qt.AlignCenter)
                self.process_table.setItem(row, 2, cpu_item)
                
                # 内存使用率
                memory_percent_item = QTableWidgetItem(f"{proc['memory_percent']:.1f}")
                memory_percent_item.setTextAlignment(Qt.AlignCenter)
                self.process_table.setItem(row, 3, memory_percent_item)
                
                # 内存MB
                memory_mb_item = QTableWidgetItem(f"{proc['memory_mb']:.1f}")
                memory_mb_item.setTextAlignment(Qt.AlignCenter)
                self.process_table.setItem(row, 4, memory_mb_item)
                
                # 状态
                status_item = QTableWidgetItem(proc['status'])
                status_item.setTextAlignment(Qt.AlignCenter)
                self.process_table.setItem(row, 5, status_item)
            
        except Exception as e:
            print(f"填充表格数据失败: {e}")
    
    def filter_processes(self):
        """过滤进程"""
        if hasattr(self, 'processes_data'):
            self.populate_table(self.processes_data)
    
    def clear_search(self):
        """清空搜索"""
        self.search_input.clear()
    
    def refresh_processes(self):
        """刷新进程列表"""
        # 这个方法会被主窗口调用来触发数据更新
        pass
    
    def on_selection_changed(self):
        """选择变化时的处理"""
        selected_items = self.process_table.selectedItems()
        self.kill_button.setEnabled(len(selected_items) > 0)
    
    def kill_selected_process(self):
        """结束选中的进程"""
        try:
            current_row = self.process_table.currentRow()
            if current_row < 0:
                QMessageBox.warning(self, "警告", "请先选择要结束的进程！")
                return
            
            # 获取选中进程的PID和名称
            pid_item = self.process_table.item(current_row, 0)
            name_item = self.process_table.item(current_row, 1)
            
            if not pid_item or not name_item:
                QMessageBox.warning(self, "错误", "无法获取进程信息！")
                return
            
            pid = int(pid_item.text())
            name = name_item.text()
            
            # 确认对话框
            reply = QMessageBox.question(
                self, 
                "确认结束进程", 
                f"确定要结束进程 \"{name}\" (PID: {pid}) 吗？\\n\\n"
                "注意：结束系统关键进程可能导致系统不稳定！",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                # 发送结束进程信号
                self.kill_process_signal.emit(pid)
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"结束进程时发生错误：{str(e)}")
    
    def show_kill_result(self, success: bool, message: str):
        """显示结束进程的结果"""
        if success:
            QMessageBox.information(self, "成功", message)
        else:
            QMessageBox.warning(self, "失败", message)